import { Controller, Get, Post, Put, Delete, Body, Request, Response, Param, Query, UseFilters, ValidationPipe, ParseIntPipe, UsePipes, UseGuards, UseInterceptors, NotFoundException, Session, ClassSerializerInterceptor } from '@nestjs/common';
import { Test } from '@src/common/entities/test.entity';
import { TestGateway } from './test.gateway'
import { ForbiddenException } from "@src/common/exceptions/forbidden.exception"
import { CustomExceptionFilter } from "@src/common/exceptions/customException.filter"
import { CreateTestDTO } from "@src/dtos/test/createTest.dto"
import { RolesGuard } from "@src/common/guards/roles.guard"
import { TestService } from '@src/modules/test/test.service'
import { ApiTags, ApiOperation, ApiParam } from '@nestjs/swagger';
import { LoggingInterceptor } from "@src/common/interceptors/logging.interceptor";
import { AuthGuard } from '@nestjs/passport';
import { AuthService } from '@src/common/auth/auth.service';
import { ResultHelper } from '@src/utils/resultHelper'
import { GetOneUserDTO } from "@src/dtos/users/getOneUser.dto"
import { UsersService } from "@src/modules/users/users.service"
const svgCaptcha = require('svg-captcha');

const Redis = require('ioredis');
const redisEvent = new Redis()
const eventsEmitter = require('events');
var emitter = new eventsEmitter.EventEmitter();

@Controller('test')
@ApiTags('Test')
@UseGuards(RolesGuard)
@UseInterceptors(LoggingInterceptor)
export class TestController {
  constructor(
    private readonly socket: TestGateway,
    private readonly testService: TestService,
    private readonly authService: AuthService,
    public readonly usersService: UsersService
  ) {

    redisEvent.on('message', function (channel, message) {
      console.log("from:", channel, ", message:", message);
    });

  }

  @Get('transaction/:id')
  @ApiOperation({
    summary: '测试数据库事务操作',
    description: ''
  })
  async testTransaction(@Param() Param) {
    console.log("Param：", Param)
    let data = await this.testService.testTransac(Param)
    return ResultHelper.send({
      code: 200,
      msg: '请求成功',
      data: data,
    })
  }

  @Get('db')
  @ApiOperation({
    summary: '查询一个test',
    description: '一定要传id'
  })
  async findOne(@Query() query) {
    return await this.testService.findOne(query.id).then(res => {
      return res
    }).catch(err => {

    })

  }

  @Post('db')
  @ApiOperation({
    summary: '创建一个test',
    description: '要传所有数据'
  })
  @UsePipes(new ValidationPipe({ transform: true }))
  async createOne(@Body() createCatDto: CreateTestDTO) {
    return await this.testService.createOne(createCatDto).then(res => {
      return {
        success: 200
      }
    }).catch(err => {

    })
  }

  @Put('db')
  @ApiOperation({
    summary: '修改一个test',
    description: '要传所有数据'
  })
  async updateOne(@Body() body: Test) {

    return await this.testService.updateOne(body).then(res => {
      return {
        success: 200
      }
    }).catch(err => {

    })

  }

  @ApiOperation({
    summary: '删除一个test',
    description: '要传所有数据'
  })
  @Delete('db')
  async deleteOne(@Query() query) {
    return await this.testService.deleteOne(query.id).then(res => {
      return {
        success: 200
      }
    }).catch(err => {

    })
  }

  @ApiOperation({
    summary: '测试自定义错误处理',
    description: ''
  })
  @Get('/custom_exception')
  @UseFilters(CustomExceptionFilter)
  async custom_exception() {
    throw new ForbiddenException()
    // return {
    //   a: 1
    // }
  }

  // 首页
  @ApiOperation({
    summary: '测试服务端渲染',
    description: ''
  })
  @Get('render_index')
  // @Render('index')
  getHello(@Response() res): any {
    res.render('./index', { msg: 'hi hi' });
  }

  @Get('not_found_exception')
  test(@Response() res): any {
    throw new NotFoundException();
  }

  @ApiOperation({
    summary: '使用拦截器统一接口api返回格式',
    description: ''
  })
  @Get('test_resulthelper')
  async test2() {
    return ResultHelper.send({
      code: 200,
      data: {
        a: 1
      }
    })
  }

  @ApiOperation({
    summary: '测试验证码',
    description: ''
  })
  @Get('get_svgcaptcha')
  getSvgCaptcha(@Request() req, @Response() res, @Session() session) {
    let captcha = svgCaptcha.create();
    session.captcha = captcha.text;
    // console.log(captcha)

    res.type('svg');
    res.status(200).send(captcha.data);

  }

  // nest.js 序列化 去掉敏感字汇 如：password 可在 entity 中配置
  @ApiOperation({
    summary: '测试字段序列化（去掉敏感字汇 如：password 可在 entity 中配置）',
    description: ''
  })
  @UseInterceptors(ClassSerializerInterceptor)
  @ApiParam({ name: 'username', description: '用户名' })
  @Get('/user/:username')
  async findOneUser(@Param() params: GetOneUserDTO) {
    let res = await this.usersService.findOne(params.username)
    return res
  }

  @ApiOperation({
    summary: '获取jwt验证码',
    description: ''
  })
  @UseGuards(AuthGuard('local'))
  @Post('login')
  async login(@Body() user) {
    console.log(user)
    const { access_token } = await this.authService.createToken(user)
    return {
      username: user.username,
      access_token
    }
  }

  @ApiOperation({
    summary: '测试jwt验证守卫',
    description: ''
  })
  @UseGuards(AuthGuard('jwt'))
  @UseFilters(CustomExceptionFilter)
  @Post('profile')
  getProfile(@Body() user, @Request() req) {
    console.log("AuthGuard('jwt') 处理结果：", req.user)
    return {
      success: 'jwt ok'
    };
  }
}
